<?php
/**
 * 测试TCP服务器内存溢出修复
 * 发送一个恶意的大长度包来测试服务器是否能正确处理
 */

$host = '127.0.0.1';
$port = 8778;

function logWithTime($msg) {
    echo '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n";
}

logWithTime("Testing memory overflow fix...");

// 创建连接
$socket = @stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 5);
if (!$socket) {
    logWithTime("Failed to connect: {$errno} {$errstr}");
    exit(1);
}

logWithTime("Connected to server");

// 构造恶意包：正常头部 + 超大长度字段
$marker = "OFZL";
$version = 0x02;
$dtype = 0x01;
$cmd = 0x01;

// 设置一个超大的长度值 (100MB)
$maliciousLen = 100 * 1024 * 1024;
$header = $marker . chr($version) . chr($dtype) . chr($cmd) . pack('V', $maliciousLen);

logWithTime("Sending malicious packet with length: " . number_format($maliciousLen) . " bytes");

// 发送恶意包头
fwrite($socket, $header);

// 等待服务器响应或断开连接
$response = fread($socket, 1024);
if ($response === false || $response === '') {
    logWithTime("Server correctly rejected the malicious packet (connection closed)");
} else {
    logWithTime("Server response: " . bin2hex($response));
}

fclose($socket);

logWithTime("Testing normal packet...");

// 测试正常包
$socket2 = @stream_socket_client("tcp://{$host}:{$port}", $errno, $errstr, 5);
if (!$socket2) {
    logWithTime("Failed to connect for normal test: {$errno} {$errstr}");
    exit(1);
}

$normalBody = '{"test": "normal packet"}';
$normalHeader = $marker . chr($version) . chr($dtype) . chr($cmd) . pack('V', strlen($normalBody));
$normalPacket = $normalHeader . $normalBody;

logWithTime("Sending normal packet...");
fwrite($socket2, $normalPacket);

$normalResponse = fread($socket2, 1024);
if ($normalResponse) {
    logWithTime("Normal packet response: " . bin2hex($normalResponse));

    // 解析响应
    if (strlen($normalResponse) >= 11) {
        $respMarker = substr($normalResponse, 0, 4);
        $respLen = unpack('V', substr($normalResponse, 7, 4))['1'];
        $respBody = substr($normalResponse, 11, $respLen);
        logWithTime("Response body: {$respBody}");
    }
} else {
    logWithTime("No response to normal packet");
}

fclose($socket2);
logWithTime("Test completed");
